#include "GameActivity.h"
#include "Observer.h"
#include "ChessBoard.h"
#include "Player.h"
#include "GameRule.h"
#include "GameFactory.h"
#include <QPoint>


#include <iostream>



bool GameActivity::isEnd = false;
bool GameActivity::isStart = false;

GameActivity::GameActivity(GameFactory * gameFactory):_gameFactory(gameFactory){}

void GameActivity::addWidget(Observer* w){
    _widgetList.push_back(w);
}
void GameActivity::notify(void){
    for(int i=0;i<_widgetList.size();i++){
        _widgetList[i]->update(this);
    }
}
Player* GameActivity::getPlayer(std::string side){
    for(int i=0;i<_playerList.size();i++){
        if(!_playerList[i]->getSide().compare(side)){
            return _playerList[i];
        }
    }
    return NULL;
}
void GameActivity::addPlayer(std::string side,ChessMethod* chessMethod){

    Player* player = _gameFactory->createPlayer();
    player->setSide(side);
    player->setChessMethod(chessMethod);
    QObject::connect((const QObject*)player->getMethod(),SIGNAL(updateUI()),this,SLOT(notify()));
    _playerList.push_back(player);

}
void GameActivity::cleanPlayer(){
    _playerList.clear();
}

void GameActivity::setPoint(int x, int y){
    _chessBoard->setPressedPoint(QPoint(x,y));
}

ChessBoard* GameActivity::getChessBoard(){
    return _chessBoard;
}

void GameActivity::onCreate(){
    //set ChessBoard
    _chessBoard = _gameFactory->createChessBoard();
    //set GameRule
    _gameRule = _gameFactory->createGameRule();
    _gameRule->setChessBoard(_chessBoard);
    _gameRule->setPlayerList(&_playerList);


}
void GameActivity::onStart(){
     GameActivity::isStart = true;
     GameActivity::isEnd = false;
     this->start();
}
void GameActivity::onStop(){
     GameActivity::isEnd = true;
     GameActivity::isStart = false;
     cleanPlayer();
}
void GameActivity::onDestroy(){

}
void GameActivity::onReset(){
    GameActivity::isEnd = true;
    GameActivity::isStart = false;
    _chessBoard->resetChessBoard();
    cleanPlayer();
    emit updateUI();

}
void GameActivity::run(){

    GameActivity::isEnd = false;
    std::cout<<"game is start"<<std::endl;
    //game start
    Player* player = _gameRule->getFirstPlayer();
    while(!GameActivity::isEnd){
         player->setIsMyTurn(true);
         player->doChess(_chessBoard,_gameRule);
         //emit updateUI();
         if(GameActivity::isEnd || _gameRule->isWin())
             break;
         player->setIsMyTurn(false);
         player = _gameRule->getNextPlayer(player);
         emit updateUI();
    }
    emit updateUI();
    std::cout<<"game is stop"<<std::endl;
}
